package com.xz.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.xz.MemberInfo;
import com.xz.VideoInfo;
import com.xz.client.VideoInfoClient;
import com.xz.entity.Order;
import com.xz.exceptionhandler.BaseException;
import com.xz.mapper.OrderMapper;
import com.xz.service.OrderService;
import com.xz.utils.HttpClient;
import com.xz.utils.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-03-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private VideoInfoClient videoInfoClient;
    @Override
    public String createOrders(String videoId, String memberId) {
        //通过远程调用根据用户id获取用户信息
        MemberInfo userInfoOrder = videoInfoClient.getMember(memberId);
        //通过远程调用根据课程id获取课信息
        VideoInfo video = videoInfoClient.getVideo(videoId);
        //创建Order对象，向order对象里面设置需要数据
        Order order = new Order();
        order.setOrderNo(OrderNoUtil.getOrderNo());//订单号
        order.setVideoId(videoId);
        order.setVideoTitle(video.getTitle());
        order.setVideoCover(video.getCover());
        order.setPrice(video.getPrice());
        order.setMemberId(memberId);
        order.setMobile(userInfoOrder.getMobile());
        order.setUsername(userInfoOrder.getUsername());
        order.setStatus(0);  //订单状态（0：未支付 1：已支付）
        order.setPayType(1);  //支付类型 ，微信1
        System.out.println(order);
        this.baseMapper.insert(order);
        //返回订单号
        return order.getOrderNo();
    }
    //生成支付二维码
    @Override
    public Map createNatvie(String orderNo) {
        try {
            //1 根据订单号查询订单信息
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            Order order = this.baseMapper.selectOne(wrapper);
            VideoInfo video=videoInfoClient.getVideo(order.getVideoId());
            //2 使用map设置生成二维码需要参数
            Map m = new HashMap();
            //做微信支付id值
            m.put("appid","wx74862e0dfcf69954");
            //商户号
            m.put("mch_id", "1558950191");
            //生成一个随机的字符串，二维码不同
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            //生成的二维码名字
            m.put("body", order.getVideoTitle()); //课程标题
            //生成二维码的唯一标识，一般用订单号
            m.put("out_trade_no", orderNo); //订单号
            //订单的价格
            m.put("total_fee", order.getPrice().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip", "127.0.0.1");
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");
            //支付的类型
            m.put("trade_type", "NATIVE");

            //3 发送httpclient请求，传递参数xml格式，微信支付提供的固定的地址
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml格式的参数，得到商户的key对参数做加密处理
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            //执行post请求发送
            client.post();

            //4 得到发送请求返回结果
            //返回内容，是使用xml格式返回
            String xml = client.getContent();

            //把xml格式转换map集合，把map集合返回
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);

            //最终返回数据 的封装
            Map map = new HashMap();
            map.put("out_trade_no", orderNo);
            map.put("video_id", order.getVideoId());
            map.put("total_fee", video.getPrice());
            map.put("result_code", resultMap.get("result_code"));  //返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));        //二维码地址

            return map;
        }catch(Exception e) {
            throw new BaseException(20001,"生成二维码失败");
        }

    }

    //查询订单支付状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            //1、封装参数
            Map m = new HashMap<>();
            m.put("appid", "wx74862e0dfcf69954");
            m.put("mch_id", "1558950191");
            m.put("out_trade_no", orderNo);
            m.put("nonce_str", WXPayUtil.generateNonceStr());

            //2 发送httpclient
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            //3 得到请求返回内容
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //6、转成Map再返回
            return resultMap;
        }catch(Exception e) {
            return null;
        }
    }
    //查询订单的状态
    //添加支付记录和更新订单状态
    @Override
    public void updateOrdersStatus(Map<String, String> map) {
        //从map获取订单号
        String orderNo = map.get("out_trade_no");
        //根据订单号查询订单信息
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        Order order = this.baseMapper.selectOne(wrapper);

        //更新订单表订单状态
        if(order.getStatus().intValue() == 1) { return; }
        order.setStatus(1);//1代表已经支付
        this.baseMapper.updateById(order);
    }
}
